package com.baitiaojun.user.service.impl;

import com.baitiaojun.api.domain.user.FollowingGroup;
import com.baitiaojun.api.domain.user.UserFollowing;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.SnowFlakeUtil;
import com.baitiaojun.user.config.properties.FollowingGroupProperties;
import com.baitiaojun.user.mapper.FollowingGroupMapper;
import com.baitiaojun.user.service.FollowingGroupService;
import com.baitiaojun.user.service.UserFollowingService;
import com.baitiaojun.user.support.RedisSupport;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @类名 FollowingGroupServiceImpl
 * @作者 白条君
 * @创建日期 2022/10/30 01:54
 * @版本 1.0
 */
@Service
public class FollowingGroupServiceImpl implements FollowingGroupService {

    @Resource
    private FollowingGroupMapper followingGroupMapper;

    @Resource
    private UserFollowingService userFollowingService;

    @Resource
    private RedisSupport redisSupport;

    @Resource
    private FollowingGroupProperties followingGroupProp;

    @Override
    public Integer getFollowingGroupIsExistsById(Long id) {
        return followingGroupMapper.selectFollowingGroupIsExistsById(id);
    }

    @Override
    public List<FollowingGroup> getFollowingGroupListByGroupIds(Set<Long> followingGroupIds) {
        return followingGroupMapper.getFollowingGroupListByIds(followingGroupIds);
    }

    @Override
    public List<FollowingGroup> getFollowingGroupByUserId(Long userid) {
        List<FollowingGroup> followingGroupList = followingGroupMapper.selectByUserId(userid);
        Collections.sort(followingGroupList, (o1, o2) -> {
            return o1.getCreatetime().compareTo(o2.getCreatetime());
        });
        return followingGroupList;
    }

    @Override
    public Object getFollowingGroupByUserId(Long userid, String token) throws ConditionException {
        String field = ConstantUtil.Field.FOLLOWING_GROUP.getKey();
        Object followingGroup = redisSupport.getHash(token, field);
        if (ObjectUtils.isNotEmpty(followingGroup)) {
            return followingGroup;
        }
        List<FollowingGroup> followingGroupList = followingGroupMapper.selectByUserId(userid);
        Collections.sort(followingGroupList, (o1, o2) -> {
            return o1.getCreatetime().compareTo(o2.getCreatetime());
        });
        redisSupport.setHash(token, field, followingGroupList);
        return followingGroupList;
    }

    @Transactional
    @Override
    public void cancelFollowingGroup(Long id, Long userId, String token)  throws Exception {
        if (ObjectUtils.isEmpty(id)) {
            throw new ConditionException("id不能为空");
        }
        if (ObjectUtils.isEmpty(followingGroupMapper.selectByPrimaryKey(id))) {
            throw new ConditionException("没有这个分组");
        }
        //检查是当前用户的此分组中否有关注用户，如果有关注用户就把这些用户移动到默认分组
        List<UserFollowing> userFollowings = userFollowingService.getUserFollowingsInThisGroup(id);
        if (ObjectUtils.isNotEmpty(userFollowings) && userFollowings.size() > 0) {
            //每个userfollowing获取默认组的id
            Long defaultGroupId = followingGroupProp.getId()[0];
            List<Long> ids = new ArrayList<>();
            userFollowings.forEach(userFollowing -> ids.add(userFollowing.getId()));
            //更新这些userfollowing的分组
            userFollowingService.batchMoveUserFollowingGroup(ids, defaultGroupId);
        }
        //给关注用户分组更新完毕以后再删除这个分组
        int res = followingGroupMapper.deleteByPrimaryKey(id);
        if (res == 0) {
            throw new ConditionException("删除分组失败");
        }
        redisSupport.setHash(token, ConstantUtil.Field.FOLLOWING_GROUP.getKey(), followingGroupMapper.selectByUserId(userId));
        redisSupport.setHash(token, ConstantUtil.Field.USER_FOLLOWING.getKey(),
                userFollowingService.getUserFollowings(UserFollowing.builder().userid(userId).build()));
    }

    @Override
    public Long addFollowingGroup(String name, Long userId, String token, UserFollowing userFollowing)  throws Exception {
        if (StringUtils.isEmpty(name)) {
            throw new ConditionException("自定义分组名称不能为空");
        }
        if (!ObjectUtils.isEmpty(followingGroupMapper.selectByUserIdAndName(userId, name))) {
            throw new ConditionException("此分组已存在");
        }
        FollowingGroup followingGroup = FollowingGroup.builder()
                .id(SnowFlakeUtil.getNextId())
                .userid(userId)
                .name(name)
                .createtime(new Date())
                .build();
        int res = followingGroupMapper.insertSelective(followingGroup);
        if (res == 0) {
            throw new ConditionException("添加用户分组失败");
        }
        //添加新的组以后往redis缓存重新添加关注用户数据
        redisSupport.setHash(token, ConstantUtil.Field.USER_FOLLOWING.getKey(), userFollowingService.getUserFollowings(userFollowing));
        redisSupport.setHash(token, ConstantUtil.Field.FOLLOWING_GROUP.getKey(), getFollowingGroupByUserId(userId));
        return followingGroup.getId();
    }
}